<?php

namespace app\controller;

use app\services\RedisQueue;
use app\services\RequestService;
use GuzzleHttp\Client;
use plugin\admin\app\controller\NetworkOrderController;
use plugin\admin\app\controller\VipOrderController;
use plugin\admin\app\model\NetworkOrder;
use plugin\admin\app\model\Option;
use plugin\admin\app\model\PayMethodModel;
use plugin\admin\app\model\VipOrder;
use plugin\admin\app\model\YbUser;
use support\Cache;
use support\Db;
use support\Log;
use support\Redis;
use support\Request;
use Webman\Push\Api;
use JasonGrimes\Paginator;

class IndexController
{
    public function index(Request $request)
    {
        static $readme;
        if (!$readme) {
            $readme = file_get_contents(base_path('README.md'));
        }
        return $readme;
    }

    public function view(Request $request)
    {
        return view('index/view', ['name' => 'webman']);
    }

    public function json(Request $request)
    {
        return json(['code' => 0, 'msg' => 'ok']);
    }

    // 网络订单
    public function order()
    {
        // 查询订单数据
        $orderData = NetworkOrderController::getOrderData();
        $vip_order = VipOrderController::orderData();
        $all_order = $this->allOrder();
        // 查询天气数据
        $weather = $this->weather();
        $network_order_data = NetworkOrder::orderBy('id','desc')->where('reward_total_price','!=',0)->limit(10)->get()->toArray();
        $vip_order_data = VipOrder::orderBy('id','desc')->limit(10)->get()->toArray();
        if (!empty($network_order_data)){
            foreach ($network_order_data as $key => $value){
                $network_order_data[$key]['customerNumber'] = mask_string($value['customerNumber']);
            }
        }
        if (!empty($vip_order_data)){
            foreach ($vip_order_data as $key => $value){
                $vip_order_data[$key]['customer_number'] = mask_string($value['customer_number']);
            }
        }
        return view('largeScreen/index',['network_order'=>$orderData,'vip_order' => $vip_order,'all_order'=>$all_order,'network_order_data'=>$network_order_data,'vip_order_data'=>$vip_order_data,'weather'=>[
            'city' => '南宁',
            'text' => $weather['text']??'晴',
            'temperature' => $weather['temperature']??'20',
            'date' => date('Y-m-d'),
        ]]);
        return json(['code'=>0,'msg'=>'ok','data'=>$orderData]);

    }

    public function weather()
    {
        $weather = Cache::get('nanning_weather');
        if(!empty($weather)){
            return $weather;
        }
        $client = new Client();
        $response = $client->get('https://api.seniverse.com/v3/weather/now.json?key=SXPhARzvrasb-m8rm&location=%E5%8D%97%E5%AE%81&language=zh-Hans&unit=c');
        $result = $response->getBody()->getContents();
        $result = json_decode($result, true);
        if (!empty($result['results'][0]['now'])){
            Cache::set('nanning_weather',$result['results'][0]['now'],3600);
            return $result['results'][0]['now'];
        }
        return [];
    }

    public function networkOrderData()
    {
        // 最近网络订单数据
        $data = NetworkOrder::orderBy('id','desc')->limit(10)->get()->toArray();
        $list = [];
        foreach ($data as $key => $value){
            $list[$key]['会员号']=$value['customerNumber'];
            $list[$key]['状态']=$value['is_reward']==1?'已免单':'未免单';
            $list[$key]['金额']=number_format($value['totalAmount'],2);
        }
        return json(['code'=>0,'msg'=>'ok','data'=>$list]);
    }

    public function allOrder()
    {
        // 商品订单
        $network_orders = NetworkOrder::select(DB::raw('COUNT(*) as count, SUM(totalAmount) as total_price, 
            SUM(CASE WHEN is_reward = 0 THEN 1 ELSE 0 END) as queue_count, 
            SUM(CASE WHEN is_reward = 1 THEN 1 ELSE 0 END) as reward_count, 
            SUM(CASE WHEN is_reward = 1 THEN reward_total_price ELSE 0 END) as reward_price'))
            ->first();

        // 合伙人订单
        $vip_orders = VipOrder::select(DB::raw('COUNT(*) as count, SUM(price) as total_price, 
            SUM(CASE WHEN is_reward = 0 THEN 1 ELSE 0 END) as queue_count, 
            SUM(CASE WHEN is_reward = 1 THEN 1 ELSE 0 END) as reward_count, 
            SUM(CASE WHEN is_reward = 1 THEN price ELSE 0 END) as reward_price'))
            ->first();

        $result = [
            'all_order_count' => $network_orders->count + $vip_orders->count,
            'order_total_price' => $network_orders->total_price + $vip_orders->total_price,
            'order_queue_count' => $network_orders->queue_count + $vip_orders->queue_count,
            'order_reward_count' => $network_orders->reward_count + $vip_orders->reward_count,
            'order_reward_price' => $network_orders->reward_price + $vip_orders->reward_price,
        ];

        // 计算免单率，处理除以0的情况
        $result['order_reward_rate'] = $result['all_order_count'] > 0 ? bcdiv($result['order_reward_count'], $result['all_order_count'], 2) * 100 . '%' : '0%';

        return $result;
    }

    // 付费会员数据
    public function vipOrder(Request $request)
    {
        $order = VipOrderController::orderData('h5');
        $reward_order_list = \think\facade\Db::table('wa_vip_order')->where('is_reward',1)->paginate(10);
        $page = $reward_order_list->render();
        return  view('index/vipOrder', ['order'=>$order,'reward_order_list'=>$reward_order_list,'page'=>$page]);

    }

    public function test(Request $request)
    {
//        $api = new Api(
//        // webman下可以直接使用config获取配置，非webman环境需要手动写入相应配置
//            'http://127.0.0.1:3232',
//            config('plugin.webman.push.app.app_key'),
//            config('plugin.webman.push.app.app_secret')
//        );
//        $orderData=[
//            'from_uid' => 2,
//            'update_list' => [
//                [
//                    'field' => 'vip_count',
//                    'value' => 9999,
//                ],
//                [
//                    'field' => 'vip_count_number',
//                    'value' => 9999,
//                ],
//            ]
//
//        ];
//// 给订阅 user-1 的所有客户端推送 message 事件的消息
//        $api->trigger('user-1', 'message', $orderData);

//dd(4444);
//        $a = RequestService::client('pospal-api2/openapi/v1/ticketOpenApi/queryMyPayMethod',json_encode([
//            'appId'=>'90F4F7FC5562A459D98F1C6B0FB82CF6'
//        ]));
//        $a = json_decode($a,true);
//        Cache::set('90F4F7FC5562A459D98F1C6B0FB82CF6'.'-pay-method',$a);
//        dd($a);

        $orderInfo = RequestService::queryMyPayMethod('90F4F7FC5562A459D98F1C6B0FB82CF6','25011211180417816104');
        foreach ($orderInfo['data'] as $key => $value){
            PayMethodModel::create([
                'showName' => $value['showName'],
                'name' => $value['name'],
                'code' => $value['code'],
            ]);
        }
        if (!empty($orderInfo['status']) && $orderInfo['status'] == 'success'){
            dd($orderInfo['data']);
            $info = json_decode($orderInfo['data'],true);
            dd($info);
        }

    }

    public function orderInfo()
    {
        $result = RequestService::client('pospal-api2/openapi/v1/orderOpenApi/queryOrderPages',json_encode([
                'appId' => '90F4F7FC5562A459D98F1C6B0FB82CF6',
                'startTime'=> '2025-01-01 00:00:00',
                'endTime' => '2025-01-01 23:59:59'
            ])
        );
        dd(json_decode($result,true));
    }

    public function userList()
    {

        $result = RequestService::client('pospal-api2/openapi/v1/customerOpenApi/queryCustomerPages',json_encode([
                'appId' => '90F4F7FC5562A459D98F1C6B0FB82CF6',
            ])
        );
        dd($result);

    }

    public function getUserInfo()
    {
        $customerNum = '1734429894636';
        $user = YbUser::where('customer_number',$customerNum)->first();
        if (empty($user)){
            $result = RequestService::client('pospal-api2/openapi/v1/customerOpenApi/queryByNumber',json_encode([
                    'appId' => '90F4F7FC5562A459D98F1C6B0FB82CF6',
                    'customerNum'=> $customerNum
                ])
            );
            $result = json_decode($result,true);
            if(!empty($result['status']) && $result['status']=='success' && !empty($result['data'])){
                YbUser::create([
                    'customer_number' => $customerNum,
                    'customer_uid' => $result['data']['customerUid'],
                ]);
            }
        }

    }

    public static function updateBalance()
    {
        $result = RequestService::client('pospal-api2/openapi/v1/customerOpenApi/updateBalancePointByIncrement',json_encode([
                'appId' => '90F4F7FC5562A459D98F1C6B0FB82CF6',
                'customerUid'=> '888981884339424346',
                'balanceIncrement' => 1,
                'dataChangeTime' => date('Y-m-d H:i:s')
            ])
        );
        dd($result);
    }

    public function getProportion()
    {
        $cache = Cache::get('proportion');
        if (empty($cache)){
            $config = Option::where('name','system_config')->value('value');
            $config = json_decode($config,true);
            $cache = $config['logo']['proportion'];
            Cache::set('proportion',$cache);
        }
        return $cache;
    }

    public function notify()
    {

    }

}
